package crud.service.impl;

//JDK库

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.ArrayList;
import java.util.List;
//工具库
import cn.hutool.cache.Cache;
import cn.hutool.cache.CacheUtil;

//框架库

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import crud.domain.SysVerify;
import crud.util.SqlUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;
//内部包

import crud.service.VerifyService;

@Service
@Slf4j
public class VerifyServiceImpl implements VerifyService {


    @Value("${cache}")
    private boolean cache;


    static Cache<String, List<SysVerify>> apiVerifyCache = CacheUtil.newLFUCache(10000);

    static final String sql = "        SELECT\n" +
            "        cv.id,\n" +
            "        cv.interface_id AS interfaceId,\n" +
            "        cv.verify_param AS verifyParam,\n" +
            "        cv.verify_regex AS verifyRegex,\n" +
            "        cv.verify_desc AS verifyDesc,\n" +
            "        cv.verify_status AS verifyStatus\n" +
            "        FROM\n" +
            "        crud_verify cv\n" +
            "        WHERE\n" +
            "        cv.verify_status = 1 and cv.interface_id = ?";


    @Override
    public List<SysVerify> getVerify(String interfaceId) {

        List<SysVerify> verifylist = new ArrayList<>();

        if (cache && apiVerifyCache.containsKey(interfaceId)) {
            verifylist = apiVerifyCache.get(interfaceId);
            return verifylist;
        }

        try {

            Connection dbCon = SqlUtil.getCrudDbCon();

            List<Object> params = new ArrayList<>();
            params.add(interfaceId);
            JSONArray rows = SqlUtil.executeQuery(dbCon, sql, params);

            for (Object o : rows) {
                JSONObject row = (JSONObject) o;
                SysVerify sysVerify = JSONObject.toJavaObject(row, SysVerify.class);
                verifylist.add(sysVerify);
            }

            if (cache) {
                apiVerifyCache.put(interfaceId, verifylist);
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }

        return verifylist;
    }


}